<template>
  <div>
    <page-header-wrapper></page-header-wrapper>
    <a-card style="margin-top: 20px">
      <a-tabs v-model="predictionStatus" @change="tabChange">
        <a-tab-pane v-for="item in tabs" :key="item.value" :tab="item.label" />
      </a-tabs>
      <div class="table-page-search-wrapper" style="margin-top: 20px">
        <a-form layout="inline" :form="searchForm">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="订单号" labelAlign="right">
                <a-textarea
                  v-decorator="['orderNos']"
                  placeholder="请输入订单号按enter回车支持多个订单查询"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="包裹号" labelAlign="right">
                <a-textarea
                  v-decorator="['packageNos']"
                  placeholder="请输入包裹号按enter回车支持多个包裹查询"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名" labelAlign="right">
                <a-input
                  v-decorator="['userName']"
                  placeholder="请输入"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <!-- <a-col :md="12" :sm="24">
              <a-form-item label="下单时间" labelAlign="right">
                <a-range-picker
                  v-decorator="['date']"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  allowClear
                />
              </a-form-item>
            </a-col> -->
            <a-col :md="(!advanced && 6) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="
                  (advanced && { float: 'right', overflow: 'hidden' }) || {}
                "
              >
                <a-button type="primary" @click.stop="getList()">
                  查询
                </a-button>
                <a-button
                  style="margin-left: 8px"
                  @click.stop="handleResetSearch"
                >
                  重置
                </a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <div class="cont_box">
      <a-table
        :columns="predictionStatus == 3 ? PredictionListColumn.filter(item=>item.dataIndex !='failReason') :PredictionListColumn"
        :dataSource="dataSource"
        :pagination="pagination"
        :rowKey="(it) => it.id"
        :loading="loading"
        binvested
      >
        <span slot="predictionStatus" slot-scope="record">
          {{ record | predictionStatus }}
        </span>
        <div slot="expandedRowRender" slot-scope="record" style="margin: 0">
          <a-row type="flex" class="_formItems_province" :gutter="12">
            <a-col
              class="desc"
              :span="6"
              v-for="(item, idx) in descriptionOpt"
              :key="idx"
            >
              <div>
                <span class="label">{{ item.title }}：</span>
                <!-- <span class="value" v-if="item.key === 'country'">
                  {{ record.country + " "+ record.state + " " + record.city + " " + record.street }}
                </span> -->
                <span class="value" v-if="item.key === 'predictionStatus'">
                  {{ record.predictionStatus | predictionStatus }}
                </span>
                <span class="value" v-else-if="item.key === 'channel'">
                  {{ record.channel }}
                </span>

                <span class="value" v-else>{{ record[item.key] || "--" }}</span>
              </div>
            </a-col>
          </a-row>
        </div>

        <span slot="operation" slot-scope="text, record">
          <a-button size="small" type="link" @click="handle(record, 'edit')">
            修改地址
          </a-button>
          <a-button size="small" type="link" @click="handle(record, 'check')">
            查看面单
          </a-button>
        </span>
      </a-table>
      <pagination
        :total="total"
        :page.sync="page"
        :size.sync="size"
        :onPageSizeChange="onPageSizeChange"
        :onShowSizeChange="onShowSizeChange"
      />
    </div>
    <editAddress
      :item="editAddrData"
      :visible="editVisibleAddress"
      :btnLoading="btnLoading"
      @ok="ok"
      @close="editVisibleAddress = false"
    ></editAddress>
  </div>
</template>

<script>
import moment from "moment";
import {
  getPredictionList,
  predictionUpdateAddr,
  predictionPrint,
} from "@/api/prediction";
import { PredictionListColumn } from "./config";
import editAddress from "./comps/editAddress.vue";
export default {
  name: "PredictionList",
  components: { editAddress },
  data() {
    return {
      searchForm: this.$form.createForm(this, {
        name: "prediction_search",
      }),
      predictionStatus: 0,
      tabs: [
        {
          label: "全部预报",
          value: 0,
        },
        {
          label: "预报成功",
          value: 3,
        },
        {
          label: "预报失败",
          value: 4,
        },
        {
          label: "待预报",
          value: 1,
        },
        {
          label: "预报中",
          value: 2,
        },
      ],
      // 高级搜索 展开/关闭
      advanced: false,
      PredictionListColumn,
      dataSource: [],
      pagination: false,
      page: 1,
      size: 50,
      total: 0,
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
      descriptionOpt: [
        {
          key: "receiveName",
          title: "收件人",
        },
        {
          key: "phone",
          title: "收件人手机号",
        },
        {
          key: "address",
          title: "收货地址",
        },
        {
          key: "packageTotalWeight",
          title: "预计重量",
        },
        {
          key: "predictionStatus",
          title: "发货状态",
        },
        {
          key: "predictionTime",
          title: "预报成功时间",
        },
        {
          key: "channel",
          title: "平台渠道",
        },
        {
          key: "shipMethod",
          title: "物流渠道",
        },
      ],

      editAddrData: {},
      editVisibleAddress: false, // 编辑收货地址弹框
      btnLoading: false,
    };
  },
  filters: {
    predictionStatus(type) {
      switch (type) {
        case 1:
          return "待预报";
        case 2:
          return "预报中";
        case 3:
          return "预报成功";
        case 4:
          return "预报失败";
      }
    },
    channelTxt(type) {
      switch (type) {
        case 2:
          return "平台渠道";
        case 3:
          return "物流渠道";
        default:
          return "--";
      }
    },
  },
  created() {
    this.getList();
  },
  methods: {
    tabChange() {
      this.page = 1;
      this.getList();
    },
    // 重置
    handleResetSearch() {
      this.page = 1;
      this.searchForm.resetFields();
      this.getList();
    },
    onPageSizeChange(page, size) {
      this.selectedRowKeys = [];
      this.page = page;
      this.getList(page, size);
    },
    onShowSizeChange(page, size) {
        this.selectedRowKeys = []
        this.page = page;
        this.size = size;
        this.getList(page, size);
    },
    handle(record, type) {
      this.editAddrData = record;
      console.log('record',record)
      if (type == "edit") this.editVisibleAddress = true;
      else {
        let loading = this.$message.loading("loading..", 0);
        predictionPrint({id:record.id})
          .then(({ code, data, message }) => {
            if (code == 200 && data) {
              this.$message.success("操作成功");
              setTimeout(() => {
                window.open(data, "_blank");
              }, 1000);
            } else {
              this.$message.error(message);
            }
          })
          .finally(() => {
            setTimeout(loading, 0.01);
          });
      }
      // console.log('record>>>', record, type);
    },
    // 获取列表
    async getList(currentPage, currentSize) {
      this.loading = true;
      const { page, size, predictionStatus } = this;
      let queryParam = this.searchForm.getFieldsValue(),orderNos = [],packageNos = []
      if(queryParam && queryParam.orderNos){
        if(queryParam.orderNos.indexOf('\n')>-1){
          orderNos = queryParam.orderNos.split('\n')
        }else{
          orderNos.push(queryParam.orderNos)
        }
      }
      if(queryParam && queryParam.packageNos){
        if(queryParam.packageNos.indexOf('\n')>-1){
          packageNos = queryParam.packageNos.split('\n')
        }else{
          packageNos.push(queryParam.packageNos)
        }
      }
      console.log(queryParam)
      let params = {
        pageNum: currentPage || page,
        pageSize: currentSize || size,
        ...queryParam,
        orderNos,
        packageNos
      };
      // 处理日期格式
      if (params?.date?.length) {
        let [beginIdx, endIdx] = params.date || [];
        beginIdx = beginIdx.format("YYYY-MM-DD HH:mm:ss");
        endIdx = endIdx.format("YYYY-MM-DD HH:mm:ss");
        Object.assign(params, { beginIdx, endIdx });
        delete params.date;
      }
      if (predictionStatus) params.predictionStatus = predictionStatus;
      // console.log('params>>>>', params);
      const res = await getPredictionList(params);
      this.total = res?.data?.total || 0;
      this.dataSource = res?.data?.list || [];
      this.loading = false;
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },

    ok(data) {
      // console.log('data--', data);
      this.btnLoading = true;
      predictionUpdateAddr(data)
        .then(({ code ,message}) => {
          if (code == 200) {
            this.editVisibleAddress = false;
            this.$message.success("操作成功");
            this.getList();
          }else{
            this.$message.error(message)
          }
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .ant-calendar-picker {
  width: 400px !important;
}
.desc {
  margin-bottom: 20px;
  .value {
    color: #000;
  }
}
</style>